package com.huaxin.hxmoduleworkorder.listener;

import com.huaxin.hxmoduleworkorder.common.enums.InspectionOrderStatus;
import com.huaxin.hxmoduleworkorder.event.InspectionOrderItemChangeEvent;
import com.huaxin.hxmoduleworkorder.mapper.InspectionOrderMapper;
import com.huaxin.hxmoduleworkorder.models.InspectionOrder;
import com.huaxin.hxmoduleworkorder.models.InspectionOrderStatusCalculationResult;
import com.huaxin.hxmoduleworkorder.service.InspectionOrderService;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class InspectionOrderItemChangeListener {

    private final InspectionOrderService inspectionOrderService;
    private final InspectionOrderMapper inspectionOrderMapper;

    public InspectionOrderItemChangeListener(InspectionOrderService inspectionOrderService,
                                             InspectionOrderMapper inspectionOrderMapper) {
        this.inspectionOrderService = inspectionOrderService;
        this.inspectionOrderMapper = inspectionOrderMapper;
    }

    @Async("inspectionOrderItemExecutor") // 使用专用线程池
    @EventListener
    @Transactional
    public void handleInspectionOrderItemChange(InspectionOrderItemChangeEvent event) {
        String orderId = event.getOrderId();
        updateOrderStatus(orderId);
    }

    /**
     * 更新工单状态
     */
    private void updateOrderStatus(String orderId) {
        InspectionOrderStatusCalculationResult statusCalculationResult = inspectionOrderMapper.calculateStatus(orderId);
        InspectionOrder order = inspectionOrderService.getById(orderId);
        order.setStatus(InspectionOrderStatus.of(statusCalculationResult.getCalculatedStatus()));
        inspectionOrderService.updateById(order);
    }
}
